'use strict';

const bcrypt = require('bcryptjs');
const SnowflakeId = require('snowflake-id').default;
const snowflake = new SnowflakeId();
const generateSnowflakeId = () => snowflake.generate();

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    // 检查是否已经存在默认部门
    const [departments] = await queryInterface.sequelize.query(
      'SELECT * FROM sys_departments WHERE name = "总公司"'
    );
    let departmentId;
    
    if (departments.length === 0) {
      // 生成部门ID
      departmentId = generateSnowflakeId();
      
      // 先创建默认部门
      await queryInterface.bulkInsert('sys_departments', [
        {
          id: departmentId,
          name: '总公司',
          parent_id: 0,
          description: '默认顶级部门',
          sort: 0,
          status: true,
          create_time: new Date(),
          update_time: new Date(),
        },
      ]);
    } else {
      departmentId = departments[0].id;
    }

    // 检查是否已经存在admin用户
    const [users] = await queryInterface.sequelize.query(
      'SELECT * FROM sys_users WHERE username = "admin"'
    );
    let userId;
    
    if (users.length === 0) {
      // 生成用户ID
      userId = generateSnowflakeId();
      
      // 加密密码
      const hashedPassword = await bcrypt.hash('admin123', 10);

      // 插入管理员数据
      await queryInterface.bulkInsert('sys_users', [
        {
          id: userId,
          username: 'admin',
          password: hashedPassword,
          real_name: '系统管理员',
          email: 'admin@example.com',
          phone: '13800138000',
          avatar: '',
          status: true,
          department_id: departmentId,
          create_time: new Date(),
          update_time: new Date(),
        },
      ]);
    } else {
      userId = users[0].id;
    }

    // 检查是否已经存在超级管理员角色
    const [roles] = await queryInterface.sequelize.query(
      'SELECT * FROM sys_roles WHERE name = "超级管理员"'
    );
    let roleId;
    
    if (roles.length === 0) {
      // 生成角色ID
      roleId = generateSnowflakeId();
      
      // 插入角色数据
      await queryInterface.bulkInsert('sys_roles', [
        {
          id: roleId,
          name: '超级管理员',
          code: 'super_admin',
          description: '系统超级管理员',
          status: true,
          create_time: new Date(),
          update_time: new Date(),
        },
      ]);
    } else {
      roleId = roles[0].id;
    }

    // 检查是否已经存在用户角色关联
    const [userRoles] = await queryInterface.sequelize.query(
      'SELECT * FROM sys_user_roles WHERE user_id = ? AND role_code = ?',
      { replacements: [userId, 'super_admin'] }
    );
    
    if (userRoles.length === 0) {
      // 生成用户角色关联ID
      const userRoleId = generateSnowflakeId();
      
      // 关联用户和角色
      await queryInterface.bulkInsert('sys_user_roles', [
        {
          id: userRoleId,
          user_id: userId,
          role_code: 'super_admin',
          create_time: new Date(),
          update_time: new Date(),
        },
      ]);
    }
  },

  async down(queryInterface, Sequelize) {
    // 删除关联数据
    await queryInterface.bulkDelete('sys_user_roles', null, {});
    // 删除角色数据
    await queryInterface.bulkDelete('sys_roles', { name: '超级管理员' }, {});
    // 删除用户数据
    await queryInterface.bulkDelete('sys_users', { username: 'admin' }, {});
    // 删除部门数据
    await queryInterface.bulkDelete('sys_departments', { name: '总公司' }, {});
  },
};
